package com.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableRabbit
@ComponentScan("com.rabbitmq")
public class RabbitmqConfig {

    /**
     * 死信交换器
     */
    private static final String DLX_EXCHANGE = "ex.do.dlx";
    /**
     * 死信队列
     */
    private static final String DLX_QUEUE = "q.do.dlx";
    /**
     * 死信key
     */
    private static final String DLX_ROUTE_KEY = "key.do.dlx";
    /**
     * 普通交换器
     */
    private static final String EXCHANGE = "ex.do";
    /**
     * 普通队列
     */
    private static final String QUEUE = "q.do";
    /**
     * 普通key
     */
    private static final String ROUTE_KEY = "key.do";



    @Bean
    public Queue queue() {
        Map<String, Object> props = new HashMap<>();
        // 消息的生存时间 10s
        props.put("x-message-ttl", 10000);
        // 设置该队列所关联的死信交换器（当队列消息TTL到期后依然没有消费，则加入死信队列）
        props.put("x-dead-letter-exchange", DLX_EXCHANGE);
        // 设置该队列所关联的死信交换器的routingKey，如果没有特殊指定，使用原队列的routingKey
        props.put("x-dead-letter-routing-key", DLX_ROUTE_KEY);
        return new Queue(QUEUE, true, false, false, props);
    }

    @Bean
    public Queue queueDlx() {
        return new Queue(DLX_QUEUE, true, false, false);
    }

    @Bean
    public Exchange exchange() {
        return new DirectExchange(EXCHANGE, true, false, null);
    }

    /**
     * 死信交换器
     *
     * @return
     */
    @Bean
    public Exchange exchangeDlx() {
        return new DirectExchange(DLX_EXCHANGE, true, false, null);
    }

    @Bean
    public Binding binding() {
        return BindingBuilder.bind(queue()).to(exchange()).with(ROUTE_KEY).noargs();
    }

    /**
     * 死信交换器绑定死信队列
     *
     * @return
     */
    @Bean
    public Binding bindingDlx() {
        return BindingBuilder.bind(queueDlx()).to(exchangeDlx()).with(DLX_ROUTE_KEY).noargs();
    }

}
